<template>
  <div class="common-container">
    <div class="common-content">
      <el-card class="comment-card" v-if="order && order.orderItems.length > 0">
        <!-- 订单信息 -->
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号:</span>
            <span class="value">{{ order.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">购买时间:</span>
            <span class="value">{{ formatDate(order.createTime) }}</span>
          </div>
        </div>
        
        <!-- 评价表单 -->
        <div class="comment-form">
          <div v-for="(item, index) in commentForm" :key="item.goodsId" class="goods-comment-item">
            <div class="goods-info">
              <img :src="item.goodsImg" alt="" class="goods-img">
              <span class="goods-name">{{ item.goodsName }}</span>
            </div>
              
            <div class="comment-content">
              <!-- 评分 -->
              <div class="rating-section">
                <span class="section-label">评分:</span>
                <el-rate v-model="item.score" :max="5" show-score style="margin-left: 10px"></el-rate>
              </div>
              
              <!-- 评价内容 -->
              <div class="content-section">
                <span class="section-label">评价内容:</span>
                <el-input 
                  type="textarea" 
                  v-model="item.content" 
                  placeholder="请输入您的评价内容" 
                  :rows="4"
                  style="width: 100%; margin-top: 10px"
                ></el-input>
              </div>
              
              <!-- 图片上传 -->
              <div class="upload-section">
                <span class="section-label">上传图片:</span>
                <el-upload
                  class="avatar-uploader"
                  action="/api/file/upload"
                  :headers="{ 'token': user.token }"
                  :show-file-list="true"
                  :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, index)"
                  :on-error="handleUploadError"
                  multiple
                  list-type="picture-card"
                  :before-upload="beforeAvatarUpload"
                  :file-list="item.imageList"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="submit-actions">
          <el-button type="primary" size="large" @click="submitComments" :disabled="loading">
            <span v-if="loading"><i class="el-icon-loading"></i> 提交中...</span>
            <span v-else>提交评价</span>
          </el-button>
          <el-button size="large" @click="cancel">取消</el-button>
        </div>
      </el-card>
      
      <!-- 加载中 -->
      <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Comment",
  data() {
    return {
      order: null,
      commentForm: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      loading: true
    };
  },
  created() {
    this.loadOrderInfo();
  },
  methods: {
    loadOrderInfo() {
      const orderId = this.$route.query.orderId;
      if (!orderId) {
        this.$message.warning('订单ID不存在');
        this.$router.push('/front/orderList');
        return;
      }
      
      this.loading = true;
      this.request.get(`/orders/${orderId}`).then(res => {
        this.loading = false;
        
        if (res.code === 200 && res.data) {
          // 字段映射，适配前端展示
          const orderData = res.data;
          this.order = {
            ...orderData,
            id: orderData.id,
            orderNo: orderData.no || orderData.orderNo,
            status: orderData.status === '已完成' ? 4 : orderData.status, // 确保状态值为数字4表示已完成
            orderItems: orderData.details ? orderData.details.map(item => ({
              productId: item.goodsId || item.productId,
              productName: item.goodsName || item.productName,
              productImg: item.imgUrl || item.img || item.productImg
            })) : []
          };
          
          // 检查订单状态是否为已完成
          if (this.order.status !== 4 && this.order.status !== '已完成') {
            this.$message.warning('该订单状态不支持评价');
            this.$router.push(`/front/orderDetail?orderId=${orderId}`);
            return;
          }
          
          // 初始化评价表单
          this.initCommentForm();
        } else {
          this.$message.error(res.msg || '获取订单信息失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取订单信息失败');
      });
    },
    
    initCommentForm() {
      this.commentForm = this.order.orderItems.map(item => ({
        goodsId: item.productId || item.goodsId, // 兼容旧数据
        goodsName: item.productName || item.goodsName,
        goodsImg: item.productImg || item.goodsImg,
        score: 5, // 默认5分
        content: '',
        imageList: []
      }));
    },
    
    handleUploadSuccess(res, file, fileList, index) {
      // 根据实际响应结构设置图片路径
      const imageUrl = res.data ? res.data.url : res;
      this.commentForm[index].imageList.push({
        name: file.name,
        url: imageUrl
      });
    },
    
    handleUploadError(err) {
      this.$message.error('图片上传失败');
    },
    
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    
    submitComments() {
      // 验证评价内容
      for (let i = 0; i < this.commentForm.length; i++) {
        const comment = this.commentForm[i];
        if (!comment.content || comment.content.trim().length === 0) {
          this.$message.warning(`请输入${comment.goodsName}的评价内容`);
          return;
        }
      }
      
      this.loading = true;
      
      // 构建评价数据
      const commentData = this.commentForm.map(comment => ({
        goodsId: comment.goodsId,
        orderId: this.order.id,
        score: comment.score,
        content: comment.content,
        images: comment.imageList.map(img => img.url).join(',')
      }));
      
      // 提交评价
      this.request.post('/comments/batch', commentData).then(res => {
        this.loading = false;
        
        if (res.code === 200) {
          this.$message.success('评价提交成功');
          // 评价成功后返回订单详情页
          this.$router.push(`/front/orderDetail?orderId=${this.order.id}`);
        } else {
          this.$message.error(res.msg || '评价提交失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('评价提交失败');
      });
    },
    
    cancel() {
      this.$router.push(`/front/orderDetail?orderId=${this.order.id}`);
    },
    
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 20px;
}

.common-content {
  margin-bottom: 20px;
}

.comment-card {
  background-color: #fff;
}

.order-info {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 100px;
  color: #909399;
}

.value {
  color: #303133;
}

.goods-comment-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.goods-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.goods-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.goods-name {
  font-size: 16px;
  color: #303133;
}

.comment-content {
  margin-left: 95px;
}

.rating-section,
.content-section,
.upload-section {
  margin-bottom: 20px;
}

.section-label {
  color: #303133;
  font-weight: 500;
}

.submit-actions {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}
</style>